package com.bigdata.demo.controller.calculationManagment;

//import com.bigdata.demo.Utils.executeutil;

import com.bigdata.demo.Utils.utils;
import com.bigdata.demo.jwtToken.PassToken;
import com.bigdata.demo.methods.Connection_BigData;
import com.bigdata.demo.methods.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

//import static com.sun.deploy.cache.Cache.copyFile;

@RestController //声明对外接口
@CrossOrigin(allowCredentials="true",allowedHeaders = "*",methods = {RequestMethod.GET,RequestMethod.POST})
public class CalculateManagement {

  utils ut = new utils();

  //更新列表
  @PassToken
  @RequestMapping (value = "/uploadFile/findAllculfile",method = RequestMethod.GET)
  public String[][] updataList(
          @RequestParam(value = "query", required = true) String query
  ){
    System.out.println(query);
    String [][]arr= ut.findAll();
    //没参数直接返回
    if(query == ""){
      return arr;
    }
    //有参数，筛选后返回
    String [][]arrQuery = ut.findQuery(arr,query);
    return arrQuery;
  }

//上传文件
  @RequestMapping (value = "/uploadFile/uploadcalculationFile",method = RequestMethod.POST)
  public String uploadFile(
          @RequestParam(value = "file", required = true) MultipartFile file
  ){
    String filePath = Public.Calculation_File_dir_server; // "/home/bigdata_platform/computation";
    String filename = ut.uploadFile(file, filePath);
    return filename;
  }

//删除缓存文件
  @RequestMapping(value = "/uploadFile/deletecache",method = RequestMethod.GET)
  public String cancelUpload(
          @RequestParam(value = "filename",required = false) String filename
  ){
    System.out.println("开始清除缓存文件"+filename);
    String delete=ut.deletecache(filename);
    return delete;
  }

  //替换原有文件
  @RequestMapping(value = "/uploadFile/replacefile",method = RequestMethod.GET)
  public String replacefile(
          @RequestParam(value = "filename",required = true) String filename
  ) throws IOException {
    System.out.println("开始替换文件 "+filename);
    String replace=ut.replaceFile(filename);
    return replace;
  }

//  //执行计算
//  @RequestMapping (value = "/uploadFile/startcalculationFile",method = RequestMethod.GET)
//  public StringBuilder startCal(
//          @RequestParam(value = "calfileName") String filename
//  ){
//    System.out.println("进来啊了");
//    System.out.println(filename);
////    String hostname = "125.221.232.243";//要连接主机的ip
////    String username = "root";//登录的用户名
////    String password = "123@bigdata";  //用户密码
////    String pri; //接口的返回，运行状态
////
////    //调用封装的类Connection_BigData，远程连接集群
////    Connection_BigData con = new Connection_BigData(hostname, username, password);
////    String path = Public.Calculation_File_dir_server;   //python文件所在目录      Calculation_File_dir_server
////    String cmd="cd "+path+"; ";                   //找到脚本所在目录
////
////    cmd += "python3 " + filename;              //脚本执行的命令
////
////    System.out.println("cmd:"+cmd);  //可以打印出来，看命令是否正确
////    pri = con.connection(cmd); //调用函数connection，连接集群，并执行cmd命令，返回运行状态
//    String catalog = Public.Calculation_File_dir_server;
//    StringBuilder run = utils.run_upload_python(filename,catalog);
//    return run;
//  }


  //获取可执行python文件名
  @RequestMapping (value = "/uploadFile/findAllfilename",method = RequestMethod.GET)
  public String[] acquireFolder(
          @RequestParam(value = "ceshi", required = true) String ceshi
  ){
    String []arr= ut.acquirefile();
    return arr;
  }

  // 创建计算
  @RequestMapping (value = "/uploadFile/createCalculation",method = RequestMethod.GET)
  public String createCal(
          @RequestParam(value = "calculationname") String calname,
          @RequestParam(value = "checkedfile") String calfilename,
          @RequestParam(value = "calculationclassification") String deployment,
          @RequestParam(value = "namespace") String namespace
  ) throws IOException {
    ut.copyfile(calname,calfilename);
    deployment = "python-wjp09";
    String pod = ut.find_pod(deployment,namespace);
    System.out.println("pod:  "+pod);
    ut.caozuo(calname,calfilename,pod,namespace,deployment);
    return "success";
  }

  //编辑文件夹名
  @RequestMapping (value = "/uploadFile/editFoldername",method = RequestMethod.GET)
  public String editFoldername(
          @RequestParam(value = "foldername") String foldername,
          @RequestParam(value = "tofoldername") String tofoldername
  ){
    ut.editFoldername(foldername,tofoldername);
    return "success";
  }

  //删除文件夹啊
  @RequestMapping (value = "/uploadFile/deleteFoldername",method = RequestMethod.GET)
  public String deleteFoldername(
          @RequestParam(value = "foldername") String foldername
  ){
    System.out.println(foldername);
    ut.deleteFoldername(foldername);
    return "success";
  }

  // 下载计算结果
   @RequestMapping (value = "/uploadFile/downloadCalResult",method = RequestMethod.GET)
  public HttpServletResponse createCal(
          @RequestParam(value = "newdirName") String calculation_name,
          HttpServletResponse response
  ) throws IOException, InterruptedException {
    String filename = calculation_name;
    String hostname = Public.hostname_bigdata;//要连接主机的ip
    String username = Public.username_bigdata;//登录的用户名
    String password = Public.password_bigdata;  //用户密码
    String pri; //接口的返回，运行状态
//
    //调用封装的类Connection_BigData，远程连接集群
    Connection_BigData con = new Connection_BigData(hostname, username, password);
    String path = Public.Calculation_File_dir_server;   //脚本所在目录
    String cmd = "cd " + path + "; ";                   //找到脚本所在目录
  //// 1. 压缩文件
    cmd += "zip" + " -q" + " -r " + (filename + ".zip ")+filename;
    System.out.println("cmd = "+cmd);
    pri = con.connection(cmd); //调用函数connection，连接集群，并执行cmd命令，返回运行状态

    InputStream fis = null;
    OutputStream toClient = null;
    try{
      File file = new File(Public.Calculation_File_dir_server+"/"+filename+".zip");
      fis = new BufferedInputStream(new FileInputStream(file));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();

      response.reset();

      response.addHeader("Access-Control-Allow-Origin", "*");
      response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      // 设置response的Header
      response.setHeader("Content-Disposition", "attachment;filename="
              + new String(filename.getBytes(),"iso-8859-1"));
      response.addHeader("Content-Length", "" + file.length());
      toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");

      toClient.write(buffer);
      toClient.flush();
      toClient.close();
      file.delete();
    } catch (IOException ex) {
      ex.printStackTrace();
    }finally {
      try { // close input stream
        if (fis != null) {
          fis.close();
        }
      } catch(Exception ex) {
      }
      try { // close output stream
        if (toClient != null) {
          toClient.close();
        }
      } catch(Exception ex) {
      }
    }
    return response;
  }

}



